package com.yf.service.im.impl;

import com.yf.channel.Session;
import com.yf.dao.im.GroupUserDao;
import com.yf.dao.UserDao;
import com.yf.entity.GroupUserEntity;
import com.yf.entity.MsgEntity;
import com.yf.entity.UserEntity;
import com.yf.response.RRException;
import com.yf.service.im.MsgGroupService;
import com.yf.service.impl.BaseServiceImpl;
import com.yf.util.GroupUtil;
import com.yf.util.SessionUtil;
import com.yf.vo.MsgGroupBackVo;
import com.yf.vo.MsgGroupUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.yf.dao.im.MsgGroupDao;
import com.yf.entity.MsgGroupEntity;
import org.springframework.transaction.annotation.Transactional;

/**
 * 群聊Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Wed Aug 29 17:47:08 CST 2018
 */
@Service
public class MsgGroupServiceImpl extends BaseServiceImpl<MsgGroupEntity> implements MsgGroupService {

    @Autowired
    private MsgGroupDao msgGroupDao;

    @Autowired
    private GroupUserDao groupUserDao;

    @Autowired
    private UserDao userDao;

    /**内部方法**/


    /**外部方法实现**/

    /**
     * back 群聊管理
     *
     * @param params
     * @return
     */
    @Override
    public List<MsgGroupBackVo> findMsgGroup(Map<String, Object> params) {
        List<MsgGroupBackVo> list = msgGroupDao.findMsgGroup(params);
        return list;
    }


    /**
     * 搜索群聊
     *
     * @param
     * @return
     */
    @Override
    public MsgGroupBackVo findMsgGroupById(Long userId, Long groupId) {
        //查询群信息
        MsgGroupEntity msgGroupEntity = msgGroupDao.get(groupId);
        if (msgGroupEntity == null) {
            throw new RRException("该群不存在");
        }

        MsgGroupBackVo msgGroupBackVo = new MsgGroupBackVo();
        BeanUtils.copyProperties(msgGroupEntity, msgGroupBackVo);

        //判断是否为该群成员
        GroupUserEntity groupUserEntity = groupUserDao.findByGroupIdAndUserId(userId, groupId);
        if (groupUserEntity != null) {
            msgGroupBackVo.setGroupUser(true);
        } else {
            msgGroupBackVo.setGroupUser(false);
        }

        return msgGroupBackVo;
    }

    /**
     * 加入群聊
     *
     * @param groupId
     * @param userId
     * @return
     */
    @Override
    public GroupUserEntity addMsgGroupUser(Long groupId, Long userId) {
        if (groupId == null) {
            throw new RRException("groupId is null");
        }
        //先判断有没有加群
        GroupUserEntity group = groupUserDao.findByGroupIdAndUserId(userId, groupId);
        if (group != null) {
            return group;
        }
        UserEntity user = userDao.get(userId);
        GroupUserEntity groupUser = new GroupUserEntity();
        groupUser.setUserId(userId);
        groupUser.setGroupId(groupId);
        groupUser.setUserAvatar(user.getAvatar());
        groupUser.setUserName(user.getName());
        groupUser.setCreateTime(new Date());
        groupUserDao.save(groupUser);
        //群聊人数+1
        MsgGroupEntity msgGroupEntity = msgGroupDao.get(groupId);
        msgGroupEntity.setNumber(msgGroupEntity.getNumber() + 1);
        msgGroupDao.update(msgGroupEntity);
        return groupUser;
    }


    /**
     * 查询当前用户的群聊信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<MsgGroupUserVo> findMsgGroupByUserId(Long userId) {
        List<MsgGroupUserVo> list = msgGroupDao.findMsgGroupByUserId(userId);
        return list;
    }


    //查询群主讲课记录
    @Override
    public List<MsgEntity> getAllGroupMsg(long groupId) {
        return msgGroupDao.getAllGroupMsg(groupId);
    }


    /************接口重写*****************/


    /**
     * 创建或者修改当前用户的群
     *
     * @param
     * @param msgGroupEntity
     * @return
     */
    @Override
    @Transactional
    public MsgGroupEntity merge(long userId, MsgGroupEntity msgGroupEntity) {
        if (msgGroupEntity.getId() != null) {   //更新操作
            MsgGroupEntity msgGroupEntity1 = msgGroupDao.get(msgGroupEntity.getId());
            if (!msgGroupEntity1.getUserId().equals(userId)) {
                throw new RRException("只有群主才能修改群");
            }
            msgGroupDao.update(msgGroupEntity);
        } else {       //创建群聊

            //保存群聊数据
            msgGroupDao.save(msgGroupEntity);
            //保存群聊成员信息,建群时只有群主
            GroupUserEntity groupUser = new GroupUserEntity();
            groupUser.setGroupId(msgGroupEntity.getId());
            groupUser.setUserId(msgGroupEntity.getUserId());
            UserEntity user = userDao.get(userId);
            groupUser.setUserAvatar(user.getAvatar());
            groupUser.setUserName(user.getName());
            groupUser.setCreateTime(new Date());
            //创建群成员
            groupUserDao.save(groupUser);
        }
        return msgGroupEntity;
    }

    //退群
    @Override
    @Transactional
    public boolean outGroup(long userId, Long gid) {
        MsgGroupEntity msgGroupEntity = msgGroupDao.get(gid);
        if (msgGroupEntity == null) {
            throw new RRException("群主已解散此群");
        }

        //群主退群
        if (msgGroupEntity.getUserId().equals(userId)) {
            groupUserDao.deleteByGroupId(gid);
            msgGroupDao.delete(gid);
            return true;
        } else {  //群成员退群
            groupUserDao.deleteByGroupIdAndUserId(userId, gid);
            return true;
        }

    }

    /**
     * 群的所有信息
     *
     * @param
     * @param gid
     * @return
     */
    @Override
    public Map findGroupUsers(long userId, long gid) {
        //所有群成员
        List<GroupUserEntity> list = groupUserDao.findByGroupId(gid);
        //群名称和群头像,群详情
        HashMap map = new HashMap();
        MsgGroupBackVo msgGroupBackVo = findMsgGroupById(userId, gid);
        map.put("groupUserList", list);
        map.put("groupAvatar", msgGroupBackVo.getAvatar());
        map.put("groupName", msgGroupBackVo.getName());
        map.put("groupInfo", msgGroupBackVo.getInfo());
        //在此群昵称
        UserEntity userEntity = userDao.get(userId);
        map.put("userName", userEntity.getName());
        map.put("userAvatar", userEntity.getAvatar());
        //是否是此群成员
        GroupUserEntity groupUserEntity = groupUserDao.findByGroupIdAndUserId(userId, gid);
        if (groupUserEntity != null) {
            map.put("isGroupUser", true);
        } else {
            map.put("isGroupUser", false);
        }

        return map;
    }

//    @Override
//    public List<MsgEntity> getFriendChatRecord(long userId, long fid,Integer chatType,Integer page,Integer limit) {
//        return msgGroupDao.getFriendChatRecord(userId,fid,chatType,page,limit); //所有记录;
//    }

    @Override
    public List<MsgGroupEntity> getMsgGroupList(Long[] groupIds) {
        List<Long> list = Arrays.asList(groupIds);
        return msgGroupDao.getMsgGroupList(list);
    }


    @Override
    @Transactional
    public MsgGroupEntity joinGroup(Long userId, Long groupId, List<Long> userIds) {
        if(userIds==null){
            userIds = new ArrayList<>();
        }
        MsgGroupEntity msgGroupEntity;
        //不存在
        if (groupId == null) {
            //DB操作 创建群
            msgGroupEntity = new MsgGroupEntity(userId);
            msgGroupDao.save(msgGroupEntity);
        }else {
            //查询用户是否已经在群里
            msgGroupEntity = msgGroupDao.get(groupId);
        }
        userIds.add(userId);
        //DB操作 创建群关系
        groupUserDao.joinGroup(msgGroupEntity.getId(), userIds);
        //IM操作 加入一个线路组
        for (Long mId : userIds) {
            Session session = SessionUtil.getSession(mId);
            if(session==null){
                continue;
            }
            GroupUtil.joinGroup(msgGroupEntity.getId(), SessionUtil.getSession(mId).getChannel());
        }
        return msgGroupEntity;
    }
}
